package com.likai.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by likai on 2018/10/11.
 * mybatis SqlSession工厂类
 */
public class SqlSessionFactoryUtil {
    //获取日志对象
    private static Logger logger = Logger.getLogger(SqlSessionFactory.class) ;

    //SqlSessionFactory对象
    private static SqlSessionFactory sqlSessionFactory = null ;

    //类线程锁
    private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class ;

    //懒汉式单例模式
    private SqlSessionFactoryUtil() {
        super();
    }

    /**
     * 初识化sqlSessionFactory
     * @return
     */
    public static SqlSessionFactory initSqlSessionFactory() {
        String resource = "mybatis-config.xml" ;
        InputStream inputStream = null ;
        try {
            inputStream = Resources.getResourceAsStream(resource) ;
        } catch (IOException e) {
            logger.error("IOException",e);
        }
        synchronized (CLASS_LOCK) {
            //如果sqlSessionFactory为空 那么创建一个新的对象
            if(sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream) ;
            }
        }

        return sqlSessionFactory ;
    }


    /**
     * 打开SqlSession
     * @return
     */
    public static SqlSession openSqlSession() {
        if(sqlSessionFactory == null) {
            initSqlSessionFactory() ;
        }

        return sqlSessionFactory.openSession() ;
    }


}
